package com.endava.exceptions.read_list_exception;

import java.io.*;
import java.util.Vector;

public class ListOfNumbers {

	private static Vector<Integer> victor;
	private static final int SIZE = 10;

	public ListOfNumbers() {
		victor = new Vector<Integer>(SIZE);
		for (int i = 0; i < SIZE; i++) {
			victor.addElement(new Integer(i));
		}
	}

	/**
	 * Writes to file integers.
	 */
	public static void writeList() {
		PrintWriter out = null;

		try {
			System.out.println("Entering try statement");
			out = new PrintWriter(new FileWriter("OutFile.txt"));
			System.out.println("File created");

			for (int i = 0; i < SIZE; i++)
				out.println("Value at: " + i + " = " + victor.elementAt(i));

		} catch (NullPointerException npe) {
			System.err.println("Caught NullPointerException: " + npe.getMessage());
		} catch (ArrayIndexOutOfBoundsException e) {
			System.err.println("Caught ArrayIndexOutOfBoundsException: " + e.getMessage());
		} catch (IOException e) {
			System.err.println("Caught IOException: " + e.getMessage());
		} finally {
			if (out != null) {
				System.out.println("Closing PrintWriter");
				out.close();
			} else {
				System.out.println("PrintWriter not open");
			}
		}
	}

	/**
	 * Reads from file integers.
	 * 
	 * @throws IOException
	 *             if the file doesn't exists
	 */
	public static void readList() throws IOException {
		BufferedReader bufferedReader = null;
		try {
			String sCurrentLine;
			bufferedReader = new BufferedReader(new FileReader("C:\\Users\\acojocar\\workspace\\ExceptionExamples\\cars.xml"));
			while ((sCurrentLine = bufferedReader.readLine()) != null) {
				System.out.println(sCurrentLine);
			}
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
		} finally {
			bufferedReader.close();
		}
	}

	public static void main(String[] args) {
		try {
			readList();
			//writeList();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
